<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Sales extends CI_Controller {

    public function index() {
        $this->load->model('Sales_model');
        
        $code = '';
        if ($this->input->post('document_code')) {
            $code = $this->input->post('document_code');
        }
        
        $vars['document_code'] = $code;
        $vars['sales_list'] = $this->Sales_model->search($code);
        $vars['menu'] = 'sales';
        $vars['content_view'] = 'sales_list';
         
        $this->load->view('template', $vars);
    }

    public function add() {
		$this->load->model('Sales_model');
        $this->load->model('Sales_details_model');
        $this->load->model('Clients_model');
		
        $vars['clients'] = $this->Clients_model->getAll();
		$vars['form_title'] = "Agregar Guía de Venta";
        $vars['content_view'] = 'sales_form';
        $vars['menu'] = 'sales';
        $this->load->view('template', $vars);
    }

    public function edit($sale_id){
		$this->load->model('Sales_model');
        $this->load->model('Clients_model');
		$this->load->model('Sales_kardex_model');
		
		$sale = $this->Sales_model->findById($sale_id);
		$datei = $sale->date;
		$date = str_replace('-', '/', $datei);
		$datef = date("d/m/Y", strtotime($date) );
		$sale->date = $datef;
		
		
		$vars['sale'] = $sale;
		$vars['saledetails'] = $this->Sales_model->findDetails($sale_id);
        $vars['clients'] = $this->Clients_model->getAll();
		$vars['warehouse_distribution'] = $this->Sales_kardex_model->findBySaleId($sale_id);
		$vars['form_title'] = "Editar Guía de Venta";
        $vars['content_view'] = 'sales_form';
        $vars['menu'] = 'sales';
        $this->load->view('template', $vars);

    }

    /*public function client() {
        $idClient = $this->input->post('id');
        $this->load->model('Clients_model');
        $dataClient = $this->Clients_model->find($idClient);
        echo json_encode($dataClient);
    }*/

    public function products() {
        $code = null;
        $description = null;
        $this->load->model('Products_model');
        if ($this->input->post('code')) {
            $code = $this->input->post('code');
        }
        if ($this->input->post('description')) {
            $description = $this->input->post('description');
        }
        $products = array();
        if ($code != null || $description != null) {
            $products = $this->Products_model->search($code, $description);
        }
        $vars['products'] = $products;
        $vars['code'] = $code;
        $vars['description'] = $description;
        $this->load->view('products_list', $vars);
    }

    public function stocks() {
        $code = null;
        
        if ($this->input->post('code')) {
            $code = $this->input->post('code');
		}

        $this->load->model('Warehouses_product_model');
        $this->load->model('Products_model');
		
		$productData = $this->Products_model->find($code);
        $listStock = $this->Warehouses_product_model->listStockByProduct($productData->products_id);
        
        $vars['priceProduct'] = $productData->price;
        $vars['codeProduct'] = $code;
        $vars['descriptionProduct'] = $description;
        $vars['listStock'] = $listStock;
        $vars['productData'] = $productData;
        $this->load->view('stock_list', $vars);
    }

    public function submit() {
		$this->load->model('Sales_model');
        $this->load->model('Sales_details_model');
		$this->load->model('Sales_kardex_model');
		$this->load->model('Products_model');
		$this->load->model('Warehouses_product_model');
		
		$numero = $this->input->post('numero');
		
		$data['document_type_id'] = 4;
		$data['document_code'] = $numero;
		
		$datei = $this->input->post('date');
		$date = str_replace('/', '-', $datei);
		$datef = date("Y-m-d", strtotime($date) );
		
		$data['date'] = $datef;
		$data['id_client'] = $this->input->post('client');
		$data['observations'] = $this->input->post('observations');
		$data['amount'] = $this->input->post('subtotalgeneral');

		$id_sale = '';
		
		if($this->input->post('id_sale')){
			$id_sale = $this->input->post('id_sale');
			
			$warehouse_distribution = $this->Sales_kardex_model->findBySaleId($id_sale);
			foreach ($warehouse_distribution as $distribution) {
				$this->Warehouses_product_model->add($distribution->product_id,
													$distribution->id_warehouse,
													$distribution->box,
													$distribution->pack,
													$distribution->unit,
													1);      
			}
			$this->Sales_kardex_model->deleteAll($id_sale);
			$this->Sales_model->deleteAllDetails($id_sale);
			
			$this->Sales_model->update_sale($id_sale, $data);
		}else{
			$id_sale = $this->Sales_model->add_sales($data);
		}
		
		$product_ids_detalle = $this->input->post('product_id_detalle');
		$total_cajas = $this->input->post('totalcaja');
		$total_paquetes = $this->input->post('totalpaguete');
		$total_unidades = $this->input->post('totalunidad');
		//$total_cost = $this->input->post('precio');
		$total_subtotalcost = $this->input->post('subtotal');
			
		for($i = 0 ; $i < count($product_ids_detalle); $i++){
			$data = array('sale_id' => $id_sale,
						 'product_id' => $product_ids_detalle[$i],
						 'box' => $total_cajas[$i],  
						 'pack' => $total_paquetes[$i],
						 'unit' => $total_unidades[$i],  
						 'amount' => $total_subtotalcost[$i], 
						);
						
            $this->Sales_details_model->addDetails($data);
		}
		
		$almacen_ids = $this->input->post('code_almacen');
		$product_id_almacenes = $this->input->post('product_id');
		$cajas_de_almacen = $this->input->post('cajas');
		$paquetes_de_almacen = $this->input->post('paquetes');
		$unidades_de_almacen = $this->input->post('unidades');
		
		for($i = 0 ; $i < count($almacen_ids); $i++){
			$productData = $this->Products_model->findById($product_id_almacenes[$i]);
			
			$listar_stock_product_almacen = $this->Sales_model->select_almacen_productos($product_id_almacenes[$i],$almacen_ids[$i]); // busca las cajas paquetes y unidades del producto "n" ubicado en el alamacen "n"
			   
			foreach ($listar_stock_product_almacen as $lis ){
					//cajas, paquetes y unidades actuales en el almacen de los productos
					$cajas = $lis->boxes;
					$paquetes = $lis->packs;
					$unidades = $lis->Units;
				   
					//recorrido de todos los inpust  generados y enviados desde el detalle de guia de venta
					$pide_caja = $cajas_de_almacen[$i];
					$pide_paquete = $paquetes_de_almacen[$i];
					$pide_unidad = $unidades_de_almacen[$i];
					
					if($pide_caja<1 && $pide_paquete<1 && $pide_unidad<1){
						continue;
					}

					$stock_actual_en_unidades = $cajas * $productData->box_packs * $productData->pack_units;
					$stock_actual_en_unidades += $paquetes * $productData->pack_units;
					$stock_actual_en_unidades += $unidades;
										
					$pedido_en_unidades = $pide_caja * $productData->box_packs * $productData->pack_units;
					$pedido_en_unidades += $pide_paquete * $productData->pack_units;
					$pedido_en_unidades += $pide_unidad;
					
					$nuevo_stock_en_unidades = $stock_actual_en_unidades - $pedido_en_unidades;
					
					$nuevo_stock_cajas = intval($nuevo_stock_en_unidades / ($productData->box_packs * $productData->pack_units));
					$residuo_cajas = $nuevo_stock_en_unidades % ($productData->box_packs * $productData->pack_units);
					
					$nuevo_stock_paquetes = intval($residuo_cajas / $productData->pack_units);
					$residuo_paquetes = $residuo_cajas % $productData->pack_units;							
					
					$data1 = array('sale_id' => $id_sale,
								'product_id' => $productData->products_id,
								'box' => $pide_caja,
								'pack' => $pide_paquete,
								'unit' => $pide_unidad,
								'id_warehouse' => $almacen_ids[$i]);
								
					$this->Sales_kardex_model->addKardexSales($data1);
					
					$this->Sales_model->edit_stock_warehouse_product($productData->products_id,
																	$almacen_ids[$i],
																	$nuevo_stock_cajas,
																	$nuevo_stock_paquetes,
																	$residuo_paquetes);
			}
		}
		$this->edit($id_sale);
    }

    public function search_code_unique() {
        $this->load->model('Sales_model');
        $document_code = $this->input->post('numero');

        echo $this->Sales_model->comparaction_code($document_code);
    }

}